#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void initConfig(ConfigFile *cfg)
{
    cfg->entries = (ConfigEntry *)malloc(INIT_CAPACITY *sizeof(ConfigEntry));
    cfg->count =0;
    cfg->capacity = INIT_CAPACITY;
}

void freeConfig(ConfigFile *cfg)
{
    free(cfg->entries);
    memset(cfg,0,sizeof(ConfigFile));
}

static int findKeyIndex(const ConfigFile *cfg,const char *key)
{
    for(int i = 0;i<cfg->count;i++)
    {
        if(strcmp(cfg->entries[i].key,key) == 0) return i;
    }
    return -1;
}

int setConfig(ConfigFile *cfg, const char *key, const char *value) 
{
    int idx = findKeyIndex(cfg,key);
    if(idx == -1)
    {
         if (cfg->count >= cfg->capacity) {
            cfg->capacity *= 2;
            cfg->entries = realloc(cfg->entries, cfg->capacity * sizeof(ConfigEntry));
        }
        idx = cfg->count++;
    }
    strncpy(cfg->entries[idx].key, key, MAX_KEY_LEN-1);
    strncpy(cfg->entries[idx].value, value, MAX_VAL_LEN-1);
    cfg->entries[idx].key[MAX_KEY_LEN-1] = '\0';
    cfg->entries[idx].value[MAX_VAL_LEN-1] = '\0';
    return 1;
}

int delConfig(ConfigFile *cfg,const char *key)
{
    int idx = findKeyIndex(cfg,key);
    if(idx != -1)
    {
        memmove(&cfg->entries[idx],&cfg->entries[idx+1],(cfg->count -idx-1)*sizeof(ConfigEntry));
        cfg->count--;
    }
    return 0;
}

int modifyConfig(ConfigFile *cfg, const char *key, const char *value) {
    int idx = findKeyIndex(cfg, key);
    if (idx != -1) {
        strncpy(cfg->entries[idx].value, value, MAX_VAL_LEN-1);
        cfg->entries[idx].value[MAX_VAL_LEN-1] = '\0';
        return 1;
    }
    return 0;
}

void printConfig(const ConfigFile *cfg) {
    for (int i = 0; i < cfg->count; i++) {
        printf("%s=%s\n", cfg->entries[i].key, cfg->entries[i].value);
    }
}

